package pers.linkong.asr.web;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import pers.linkong.asr.domain.RecordBean;
import pers.linkong.asr.domain.RecordNumBean;
import pers.linkong.asr.service.RecordService;
import pers.linkong.asr.util.LayPage;
import pers.linkong.asr.util.ResultInfo;
import pers.linkong.asr.util.TimeKit;
import pres.linkong.as.fr.FaceRecognition;
import sun.misc.BASE64Decoder;


    /**
    * @ClassName: RecordController
    * @Description: TODO(记录与检测专用类)
    * @author 独木林空
    * @date 2018年8月8日
    *
    */
    
@SuppressWarnings("restriction")
@Controller
@RequestMapping("/record")
public class RecordController {
	
	@Autowired
	private RecordService recordService;
	
	@RequestMapping("/recognition")
	@ResponseBody
	public ResultInfo recognition(@RequestParam(value = "cidSublevel") int cidSublevel, 
			@RequestParam(value = "lesson") int lesson, 
			@RequestParam(value = "testImage") String testImage,
			HttpServletRequest request,HttpServletResponse response) throws IOException{
		try{
			// 路径与值初始化
			RecordBean record = new RecordBean();
			String path = request.getServletContext().getRealPath("/WEB-INF/");
			System.out.println(path);
			int sid,imgid;
			
			// 将传递的图像保存为文件
			BASE64Decoder decoder = new BASE64Decoder();    
	        byte[] b = decoder.decodeBuffer((String) testImage);    

	        ByteArrayInputStream bais = new ByteArrayInputStream(b);    
	        BufferedImage bi = ImageIO.read(bais);    
	        BufferedImage newBufferedImage = new BufferedImage(bi.getWidth(),
	        		bi.getHeight(), BufferedImage.TYPE_INT_RGB);
	        // TYPE_INT_RGB:创建一个RBG图像，24位深度，成功将32位图转化成24位
	        newBufferedImage.createGraphics().drawImage(bi, 0, 0, Color.WHITE, null);
	    
	        File w2 = new File(path+"Test/","test.jpg");    
	        ImageIO.write(newBufferedImage,"jpg",w2);  
	        
	        // 根据图像文件像返回最接近的学生的学号		
			FaceRecognition fr = new FaceRecognition();
			Object[] result = fr.Recognition2(1, path);
			
			imgid = Integer.parseInt(result[0].toString());
			System.out.println("图片序号：" + imgid);
			if(imgid == -1){
				return ResultInfo.data(0, "未找到匹配的面部数据，请重试");
			}
			sid = this.recordService.getSidByImgId(imgid);
			System.out.println(sid);
			
			long count = this.recordService.getStudentCountByCsid(sid, cidSublevel);
			if(count == 0){
				return ResultInfo.data(3, "当前班级没有该生");
			}
			
			record.setCidSublevel(cidSublevel);
			record.setLesson(lesson);
			record.setSid(sid);
			
			long count2 = this.recordService.getRidCountByRecord(record);
			System.out.println(count2);
			if(count2 != 0){
				return ResultInfo.data(2, "您已经签到过了");
			} else {
				long count3 = this.recordService.getRidCountByRecord2(record);
				if(count3 == 0){
					this.recordService.addRecord(record);
					return ResultInfo.data(1, record.getSid() + "记录成功");
				} else{
					// 判定为早退
					this.recordService.updateRecordByZaotui(record);
					return ResultInfo.data(1, sid + "签离成功");
				}
			}
		}
		catch(Exception e){
			e.printStackTrace();
			return ResultInfo.data(0, "发生异常，保存失败，请稍后再试");
		}
	}
	
	@RequestMapping("/add")
	@ResponseBody
	public ResultInfo addRecord(RecordBean record, HttpSession session) throws IOException{
		try{
			// 需要提供cidSublevel、lesson、sid
			System.out.println("试图手动记录" + record.getSid() + "-" + record.getCidSublevel());
			Object tid = session.getAttribute("loginTid");
			if(tid==null || tid=="" || tid == "null"){
				return ResultInfo.data(0, "手动签到需要教师登录");
			}
			long count = this.recordService.getStudentCountByCsid(record.getSid(), record.getCidSublevel());
			if(count == 0){
				return ResultInfo.data(3, "当前班级没有该生");
			}
			
			long count2 = this.recordService.getRidCountByRecord(record);
			if(count2 != 0){
				return ResultInfo.data(2, "您已经签到过了");
			} else {
				long count3 = this.recordService.getRidCountByRecord2(record);
				System.out.println("签离判断" + count3);
				if(count3 == 0){
					this.recordService.addRecord(record);
					return ResultInfo.data(1, record.getSid() + "记录成功");
				} else{
					// 判定为早退
					this.recordService.updateRecordByZaotui(record);
					return ResultInfo.data(1, record.getSid() + "签离成功");
				}
			}
		}
		catch(Exception e){
			e.printStackTrace();
			return ResultInfo.data(0, "发生异常，保存失败，请稍后再试");
		}
	}
	
	@RequestMapping("/update")
	@ResponseBody
	public ResultInfo updateRecord(RecordBean record) throws IOException{
		try{
			System.out.println(record.getRid());
			this.recordService.updateRecord(record);
			return ResultInfo.data(1, "状态改变成功");
		}
		catch(Exception e){
			e.printStackTrace();
			return ResultInfo.data(0, "发生异常，保存失败，请稍后再试");
		}
	}
	
	// 分页查询
	@RequestMapping("/findRecordByPage")
	@ResponseBody
	public LayPage findRecordByPage(String rid, String sid, String sname, String cid, String createdate, String flag,
			long page, long limit,  HttpSession session) throws Exception{
		RecordBean record = new RecordBean();
		long start;
		
		start = (page - 1) * limit;	

		// trim方法可以删除字符串前端和后端的空格（含tab键产生的空格）
		if(rid != null && rid != ""){
			record.setRid(Integer.parseInt(rid.trim()));
		}
		if(cid != null && cid != ""){
			record.setCid(Integer.parseInt(cid.trim()));
		}
		if(sid != null && sid != ""){
			record.setSid(Integer.parseInt(sid.trim()));
		}
		if(sname != null && sname != ""){
			record.setSname(sname.trim());
		}
		if(createdate != null && createdate != ""){
			record.setCreatedate(TimeKit.YMDFormatTS(createdate));
		}
		if(flag != null && flag != ""){
			record.setFlag(Integer.parseInt(flag.trim()));
		}
		
		List<RecordBean> records
			= this.recordService.findRecordByPage(record, start, limit);
		long count = this.recordService.getRecordCount(record);
		System.out.println("RC:"+count);
		return LayPage.data(0, "", count, records);
	}
	

	// 检测页分页
	@RequestMapping("/findDetRecByPage")
	@ResponseBody
	public LayPage findDetRecByPage(int cidSublevel, String classid,
			long page, long limit,  HttpSession session) throws Exception{
		long start;
		start = (page - 1) * limit;	
		List<RecordBean> records
			= this.recordService.findDetRecByPage(cidSublevel, classid, start, limit);
		long count = this.recordService.getDetRecCount(classid);
		System.out.println("RC:"+count);
		return LayPage.data(0, "", count, records);
	}
	
	// 根据id查询
	@RequestMapping("/getRecordById")
	@ResponseBody
	public RecordBean getRecordById(int rid) throws Exception{
		System.out.println(rid);
		return this.recordService.getRecordById(rid);
	}
	
	// 根据id删除
	@RequestMapping("/deleteRecordById")
	@ResponseBody
	public ResultInfo deleteRecordById(int rid) throws IOException {
		try{
			this.recordService.deleteRecord(rid);
			return ResultInfo.data(1, "删除成功");
		}
		catch(Exception e){
			e.printStackTrace();
			return ResultInfo.data(0, "发生异常，删除失败，请稍后再试");
		}
	}
	
	// 根据flag分类获取记录条数
	@RequestMapping("/getRecordNum")
	@ResponseBody
	public RecordNumBean getRecordNum(int cidSublevel, String classid) throws IOException {
		try{
			RecordNumBean numBean = this.recordService.getRecordNum(cidSublevel, classid);
			numBean.setWeidao(numBean.getSnum()-numBean.getYidao()-numBean.getChidao()-numBean.getZaotui());
			return numBean;
		}
		catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	
	// 签离功能
	@RequestMapping("/updateDetRecord")
	@ResponseBody
	public ResultInfo updateDetRecord(int cidSublevel, int flag) throws IOException {
		try{
			this.recordService.updateDetRecord(cidSublevel, flag);
			if(flag == 1){
				return ResultInfo.data(1, "签离已启动,之前为已到状态的同学请再次签到");
			} else {
				return ResultInfo.data(1, "签离已启动,之前为已到、迟到状态的同学请再次签到");
			}
		}
		catch(Exception e){
			e.printStackTrace();
			return ResultInfo.data(0, "发生异常，删除失败，请稍后再试");
		}
	}
}
